package pl.pawluk.inz.web;

import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import pl.pawluk.inz.dto.CourseDTO;
import pl.pawluk.inz.dto.GroupDTO;
import pl.pawluk.inz.dto.UserDTO;
import pl.pawluk.inz.services.WelcomeService;
import pl.pawluk.inz.utils.AuthoritiesEnum;
import pl.pawluk.inz.web.model.SelectableListDataModel;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.model.ListDataModel;
import java.io.Serializable;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: mandp
 * Date: 19.04.13
 * Time: 19:49
 * To change this template use File | Settings | File Templates.
 */
@Component
@Scope("session")
public class UsersBean extends BaseBean {

    @Autowired
    private WelcomeService welcomeService;

    @Value("${version}")
    private String version;

    private Long courseId;

    private final Map<String, String> authorities = AuthoritiesEnum.getRoles();

    @Override
    protected void insertOrUpdate() {
        if (user.getId() != null) {
            welcomeService.updateUser(user);
        } else {
            welcomeService.createUser(user);
        }
    }

    private UserDTO user;

    public ListDataModel<UserDTO> getUsers() {
        return new SelectableListDataModel<UserDTO>(welcomeService.getAllUsers());
    }

    public String getVersion() {
        return version;
    }

    public UserDTO getUser() {
        return user == null ? user = new UserDTO() : user;
    }

    public void setUser(UserDTO user) {
        this.user = user;
    }

    public void onRowUnselect(UnselectEvent event) {
        user = null;
    }

    @Override
    public void onRowSelect(SelectEvent event) {
        user = (UserDTO) event.getObject();
    }

    @Override
    public void createNew() {
        user = null;
    }

    @Override
    public void delete() {
        welcomeService.deleteUser(user);
    }

    public Map<String, String> getAuthorities() {
        return authorities;
    }

    public Long getCourseId() {
        return courseId;
    }

    public void setCourseId(Long courseId) {
        this.courseId = courseId;
    }
}
